import axios, { AxiosError, type Method } from 'axios'

import { useUserStore } from '@/stores'
import { showToast } from 'vant'
import router from '@/router'

export const baseURL = 'https://consult-api.itheima.net/'
const instance = axios.create({
  //  1. 基础地址，超时时间
  baseURL: 'https://consult-api.itheima.net/',
  timeout: 5000
})

instance.interceptors.request.use(
  (config) => {
    //  2. 携带token
    const store = useUserStore()
    const token = store.user?.token
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    //  3. 处理业务失败
    if (res.data?.code !== 10000) {
      showToast(res.data?.message || '业务失败')
      return Promise.reject(res.data)
    }
    //  4. 摘取核心响应数据
    return res.data
  },
  (err: AxiosError) => {
    // 5. 处理401错误
    if (err.response?.status === 401) {
      const store = useUserStore()
      store.delUser()
      // 跳转登录，带上接口失效所在页面的地址，登录完成后回跳使用
      router.push({
        path: '/login',
        query: { returnUrl: router.currentRoute.value.fullPath }
      })
    }
    return Promise.reject(err)
  }
)

export default instance

// 4. 请求工具函数
type Data<T> = {
  code: number
  message: string
  data: T
}
// 4. 请求工具函数
export const request = <T>(
  url: string,
  method: Method = 'get',
  submitData?: object
) => {
  return instance.request<T, Data<T>>({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
  })
}
